package com.study.forumsystemproject.service.impl;

import com.study.forumsystemproject.common.Result;
import com.study.forumsystemproject.common.ResultCode;
import com.study.forumsystemproject.dao.ArticleMapper;
import com.study.forumsystemproject.dao.UpvoteMapper;
import com.study.forumsystemproject.exception.ApplicationException;
import com.study.forumsystemproject.model.*;
import com.study.forumsystemproject.service.IArticleService;
import com.study.forumsystemproject.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * program: forum-system-project
 * <p>
 * description: 文章接口的实现类
 * <p>
 * author: xiaoxie
 * <p>
 * create: 2024-08-17 11:22
 **/
@Service
@Slf4j
public class ArticleImpl implements IArticleService {
    @Autowired
    private BoardImpl boardImpl;
    @Autowired
    private UserImpl userImpl;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private UpvoteMapper upvoteMapper;
    @Override
    public void addArticle(Article article) {
        //参数校验
        if(article == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //获取用户对象.
        User userInfo = userImpl.getUserInfo(article.getUserId());
        if(userInfo == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //判断是否禁言
        User.isBean(userInfo.getState());
        //更新用户表
        userImpl.addOneArticleCountById(userInfo.getId(),userInfo.getArticleCount());
        //获取版块信息
        Board board = boardImpl.getBoardById(article.getBoardId());
        if(board == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //判断是否禁言
        Board.isBean(board.getState());
        //更新版块表
        boardImpl.addOneArticleById(board.getId(),board.getArticleCount());
        //插入文章
        //定义好默认参数,降低数据库的性能消耗
        article.setVisitCount(0);
        article.setReplyCount(0);
        article.setLikeCount(0);
        article.setState(0);
        article.setDeleteFlag(0);
        int row = articleMapper.insertSelective(article);
        if(row != 1) {
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_CREATE_ARTICLE));
        }
        //更新点赞表
        int row1 = upvoteMapper.insert(userInfo.getId(),article.getId());
        if(row1 != 1) {
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_CREATE));
        }
    }


    @Override
    public PageInfo getAllArticles(ResultPage resultPage) {
        Integer total = articleMapper.total();
        if(total == null || total < 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        List<Article> articles = articleMapper.selectAll(resultPage.getOffset(), resultPage.getPageSize());
        PageInfo pageInfo = new PageInfo();
        pageInfo.setTotal(total);
        pageInfo.setPages(resultPage);
        pageInfo.setItems(articles);
        return pageInfo;
    }

    @Override
    public  PageInfo getListByBoardId(Long boardId,ResultPage resultPage) {
        if(boardId == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Board board = boardImpl.getBoardById(boardId);
        if(board == null) {
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        List<Article> articles = articleMapper.selectByBoardId(boardId, resultPage.getOffset(), resultPage.getPageSize());
        PageInfo pageInfo = new PageInfo();
        pageInfo.setTotal(board.getArticleCount());
        pageInfo.setPages(resultPage);
        pageInfo.setItems(articles);
        return pageInfo;
    }


    @Override
    public Article selectDetailsByArticleId(HttpServletRequest request,Long id) {
        //非空校验
        if(id == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //通过帖子id查询信息
        Article article = articleMapper.selectDetailsByArticleId(id);
        //非空校验
        if(article == null) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //更新数据库查看帖子数量+1
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount()+1);
        articleMapper.updateByPrimaryKeySelective(updateArticle);
        //更新之前获取的数据的查看帖子数量+1
        article.setVisitCount(article.getVisitCount()+1);
        //更新是否点赞
        Long userId = ((Number)JwtUtil.getValue(request,"UserId")).longValue();
        Integer Upvote = upvoteMapper.selectByArticleIdAndUserId(userId,article.getId());
        if(Upvote == null) {
            upvoteMapper.insert(userId,article.getId());
        }
        Upvote = upvoteMapper.selectByArticleIdAndUserId(userId,article.getId());
        if(Upvote == 1) {
            article.setIsUpvote(1);
        }else {
            article.setIsUpvote(0);
        }
        return article;
    }


    @Override
    public void modifyArticle(Long id, String title, String content) {
        //参数校验
        if(id == null || !StringUtils.hasLength(title) || !StringUtils.hasLength(content)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //通过参数构造article对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setTitle(title);
        updateArticle.setContent(content);
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        //校验是否修改成功
        if(row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(Result.fail(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public Article getArticleById(Long id) {
        //参数校验
        if(id == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //通过id获取帖子信息
       return articleMapper.selectByPrimaryKey(id);
    }


    @Override
    public Boolean UpvoteByArticleId(HttpServletRequest request, Long id) {
        Boolean isUpvote = false;
        //非空校验
        if(id == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //通过id获取帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);
        //校验
        if(article == null || article.getDeleteFlag() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //查看帖子状态
        if(article.getState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_STATE.toString());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_ARTICLE_NOT_STATE));
        }
        Article updateArticle = new Article();
        updateArticle.setId(id);
        //判断是否已点赞
        Long userId = ((Number)JwtUtil.getValue(request,"UserId")).longValue();
        Integer Upvote = upvoteMapper.selectByArticleIdAndUserId(userId,article.getId());
        if(Upvote == null) {
            upvoteMapper.insert(userId,article.getId());
        }
        Upvote = upvoteMapper.selectByArticleIdAndUserId(userId,article.getId());
        if(Upvote == 0) {
            //未点赞
            upvoteMapper.updateByArticleIdAndUserId(1,userId,article.getId());
            updateArticle.setLikeCount(article.getLikeCount() + 1);
            isUpvote = true;
        }else {
            //已点赞
            upvoteMapper.updateByArticleIdAndUserId(0,userId,article.getId());
            updateArticle.setLikeCount(article.getLikeCount() - 1);
        }
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(Result.fail(ResultCode.ERROR_SERVICES));
        }
        return isUpvote;
    }

    @Override
    public void subArticle(Long id) {
        //参数校验
        if(id == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        //获取用户对象.
        User userInfo = userImpl.getUserInfo(article.getUserId());
        if(userInfo == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //判断是否禁言
        User.isBean(userInfo.getState());
        //更新用户表
        userImpl.subOneArticleCountById(article.getUserId());
        //获取版块信息
        Board board = boardImpl.getBoardById(article.getBoardId());
        if(board == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //判断是否禁言
        Board.isBean(board.getState());
        //更新版块表
        boardImpl.subOneArticleById(board.getId());
        //设置为删除
        article.setDeleteFlag(1);
        int row = articleMapper.updateByPrimaryKeySelective(article);
        if(row != 1) {
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_CREATE_ARTICLE));
        }
    }

    @Override
    public void addOneReply(Long id) {
        //参数校验
        if(id == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //获取article对象
        Article article = articleMapper.selectByPrimaryKey(id);
        //判断文章是否存在,以及文章的状态
        if(article == null || article.getDeleteFlag() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //校验状态
        if(article.getState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_STATE.toString());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_ARTICLE_NOT_STATE));
        }
        //构造更新的帖子对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setReplyCount(article.getReplyCount() + 1);
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(Result.fail(ResultCode.ERROR_SERVICES));
        }
    }
    @Override
    public List<Article> selectDetailsByUserId(Long userId) {
        if(userId == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //获取一下User对象校验一下
        User userInfo = userImpl.getUserInfo(userId);
        if(userInfo == null || userInfo.getDeleteFlag() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //开始查询
       return articleMapper.selectDetailsByUserId(userId);
    }
}
